package com.imooc.utils;

import com.sfa.common.properties.WechatProperties;
import com.sfa.common.utils.http.HttpUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description 小程序工具类
 * @Author 顾志杰
 * @Date 2025/3/10 14:20
 */
@Component
public class WechatUtils {

    @Autowired
    private WechatProperties properties;


    /**
     * 获取 accesstoken
     * @return
     */
    public String getAccessToken(){
        Map<String, Object> result = RestTemplateUtil.get("https://api.weixin.qq.com/cgi-bin/token",
                "appid=" + properties.getAppid() +
                        "&" +
                        "grant_type=" + properties.getGrantType() +
                        "&" +
                        "secret=" + properties.getSecret(),Map.class);
        String accessToken = (String)result.get("access_token");
        if(StringUtils.isBlank(accessToken)){
            throw new RuntimeException("获取 access_token 异常");
        }
        return  accessToken;
    }

    /**
     * 前端传code 查询用户电话号
     * @param code
     * @return
     */
    public String getUserPhoneNumber(String code){
        HashMap<String, String> paramMap = new HashMap<String,String>(){{
            put("code",code);
        }};
        Map result = RestTemplateUtil.post("https://api.weixin.qq.com/wxa/business/getuserphonenumber?" +
                "access_token=" + getAccessToken(),
                paramMap, Map.class).getBody();
        if(0 != (Integer) result.get("errcode")){
            throw new RuntimeException("获取电话号失败");
        }

        Map<String,Object> phoneInfo = (Map<String, Object>) result.get("phone_info");
        return (String) phoneInfo.get("phoneNumber");
    }
}
